package demo.netflix.discovery.util;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RateLimiterDemo2 {

    private static Logger logger = LoggerFactory.getLogger(RateLimiterDemo2.class);

    ExecutorService executorService = Executors.newFixedThreadPool(16);

    @Test
    public void test1() {
        RateLimiter limiter = new RateLimiter(TimeUnit.SECONDS);
        AtomicInteger cnt = new AtomicInteger(0);
        while (true) {
            executorService.submit(() -> {
                if (limiter.acquire(6, 2)) {
                    logger.info("获取令牌成功：{}", cnt.incrementAndGet());
                } else {
                    logger.trace("获取令牌失败");
                }
            });
        }
    }

    @Test
    public void test2() {
        RateLimiter2 limiter = new RateLimiter2(6, 2, TimeUnit.SECONDS);
        AtomicInteger cnt = new AtomicInteger(0);
        while (true) {
            executorService.submit(() -> {
                if (limiter.acquire()) {
                    logger.info("获取令牌成功：{}", cnt.incrementAndGet());
                } else {
                    logger.trace("获取令牌失败");
                }
            });
        }
    }
}
